package com.example.websocket.controller;

import com.example.websocket.manager.WebSocketServer;
import com.example.websocket.model.table.User;
import com.example.websocket.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by liulanhua on 2018/9/25.
 */
@Slf4j
@RestController
@RequestMapping("/websocket")
public class WebsocketController {

    @Autowired
    private UserService userService;


    @GetMapping("/{room}/{id}")
    public ModelAndView websocket(@PathVariable("room") String room,@PathVariable("id") String fromUserId) {
        log.info(">>>Hello, this is websocket page !");
        User findUser = userService.findUser(new User(fromUserId));
        return new ModelAndView("/websocket").addObject("user", findUser).addObject("room", room);
    }


    @PostMapping("/push/{room}/{toUserId}")
    public ResponseEntity<String> pushToWeb(String message, @PathVariable String toUserId, @PathVariable String room, HttpServletRequest request)
            throws IOException {
        log.info(">>>request url:{}, sessionId:{}, message:{}", "/push", request.getSession().getId(), message);
        WebSocketServer.sendInfo(message, toUserId,room);
        return ResponseEntity.ok(">>>MSG SEND SUCCESS");
    }


}
